package com.infinitegroup.findmystuff.presenters;

import android.content.Context;

import com.infinitegroup.findmystuff.models.*;
import com.infinitegroup.findmystuff.views.*;

/**
 * This class controls all logic associated with the login screen
 * @author Rohit
 *
 */
public class LoginPresenter {

	private LoginView view;
	private Account account;
	private int attempts = 0;
	
	/**
	 * Constructor
	 * @param view The view associated with this presenter.
	 */
	public LoginPresenter(LoginView view) {
		this.view = view;
		account = new AccountLink("", (Context) view);
		account.checkSuperAdmin(); //only for this presenter! checks if a super-admin is already created.
	}
	
	/**
	 * Handles the event "Login Click"
	 * @param username
	 * @param password
	 */
	public void handleLoginClick(String username, String password){
		attemptLogin(username, password);
	}
	
	
	/**
	 * Retrieves account info associated with username and checks if the user should be logged in.
	 * Also handles Exceptions associated with connection failures.
	 * @param username the user's username
	 * @param password the user's password.
	 */
	public void attemptLogin(String username, String password) {
		try { // try to establish a link to existing account.
			account.refresh(username); // get account details associated with this newly entered username;
			System.out.println(""+attempts);
			if (account.getUsername().equals("")){ // no details were fetched.
				view.displayMessage("No such user exists");
			} else { // details were successfully fetched. Decide next course of action.
				if (account.getPassword().equals(password) && account.isActive()){ // all is fine. move to home
					decideProperHome();
					
				} else {
					if (!account.isActive()){
						view.displayMessage("Your account is not active");
					} else { //acount is active but password isn't right. uh oh.
						attempts++;
						if (attempts >= 3 && (!username.equals("superadmin"))) {
							account.deactivate();
							view.displayMessage("You have exceeded three attempts");
							view.advanceToLocked(); // go to lock screen after 3 failed attempts.
							attempts = 0;
						} else {
							view.retry();
						}
					}
				}
			}
		} 
		catch (Exception e){
			e.printStackTrace();
			view.displayMessage("Could not establish connection to server");
		}
	}
	
	/**
	 * Decides whether the user is an admin or not, and directs the app to the correct home screen. 
	 */
	public void decideProperHome(){
		if (account.isAdmin()){
			view.advanceToAdminHome(account.getUsername());
		} else {
			view.advanceToHome(account.getUsername());
		}
	}
	
	/**
	 * Takes the user to the registration screen.
	 */
	public void handleRegisterClick() {
		view.advanceToRegistration();
		
	}

}
